<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="引流赠品" prop="giftActivityIds">
        <div class="flex flex-col">
          <el-button type="success" plain @click="openGiftActivitySelect()">选择引流赠品</el-button>
          <div
            v-if="giftActivities && giftActivities.length > 0"
            class="flex items-center flex-wrap py-10px"
          >
            <b class="text-gray">已选赠品：</b>
            <el-tag v-for="item in giftActivities" :key="item.id">{{ item.name }}</el-tag>
          </div>
          <div
            v-else-if="formData.giftActivityNames && formData.giftActivityNames.length > 0"
            class="flex items-center flex-wrap py-10px"
          >
            <b class="text-gray">已选赠品：</b>
            <el-tag v-for="item in formData.giftActivityNames" :key="item">{{ item }}</el-tag>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="赠送条件" prop="giveUsePrice">
        <el-input-number
          v-model="computedGiveUsePrice"
          :min="0"
          :step="1"
          :precision="2"
          placeholder="请输入满送金额"
          class="!w-240px"
        >
          <template #prefix>下单满</template>
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <GiftSelect ref="giftSelectFormRef" @change="handleGiftSelect" />
  </el-drawer>
</template>

<!--suppress HtmlUnknownAttribute -->
<script setup lang="ts" name="GiftScanConfigForm">
import * as GiftScanConfigApi from '@/api/promotion/gift/GiftScanConfigApi'
import { fenToYuan, yuanToFen } from '@/utils'
import GiftSelect from '@/views/mall/promotion/gift/GiftSelect.vue'

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  giftActivityIds: undefined,
  giftActivityNames: undefined,
  giveUsePrice: 0
})
const formRules = reactive({
  giftActivityIds: [{ required: true, message: '请选择引流赠品', trigger: 'blur' }]
})
const formRef = ref()

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GiftScanConfigApi.getDetailById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const computedGiveUsePrice = computed({
  get: () => {
    return Number(fenToYuan(formData.value.giveUsePrice))
  },
  set: (value) => {
    formData.value.giveUsePrice = yuanToFen(value)
  }
})

const giftSelectFormRef = ref()
const giftActivities = ref<any>([])
const openGiftActivitySelect = () => {
  giftSelectFormRef.value?.open()
}
const handleGiftSelect = async (e: any[]) => {
  console.debug(JSON.stringify(e))
  if (!e?.length) {
    message.error('请选择引流赠品')
    return
  }
  giftActivities.value = e
  formData.value.giftActivityIds = e.map((item) => item.id)
  await formRef.value.validate()
}

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await GiftScanConfigApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await GiftScanConfigApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    giftActivityIds: undefined,
    giftActivityNames: undefined,
    giveUsePrice: 0
  }
  formRef.value?.resetFields()
}
</script>
